<template>
    <div>
        <a-modal v-model:visible="modalVisible" :title="fromTitle" @ok="handleOk" :confirm-loading="confirmLoading">
            <div>
                <a-form :model="form" ref="formRef">
                    <a-form-item label="选择卡数" :rules="[{ required: true, message: '请选择卡数' }]">
                        <a-select v-model:value="gpuNum" :options="gpuNumOptions" style="width:180px;"></a-select>
                    </a-form-item>

                    <a-form-item label="付费方式" name="skuName" :rules="[{ required: true, message: '请选择付费方式' }]"
                        v-if="fromTitle == '确认开机' && form.skuName != 'free'">
                        <a-select v-model:value="form.skuName" style="width:180px;" @change="selectSkuName">
                            <a-select-option value="payg">按量付费</a-select-option>
                            <a-select-option value="daily">包天</a-select-option>
                            <a-select-option value="weekly">包周</a-select-option>
                            <a-select-option value="monthly">包月</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item label="GPU" class="mb-8" v-if="form.skuName == 'free'">
                        机主机器
                    </a-form-item>

                    <a-form-item label="时长"
                        v-if="['daily', 'weekly', 'monthly'].includes(form.skuName) && fromTitle == '确认开机'">
                        <a-input-number v-if="form.skuName == 'monthly'" v-model:value="form.duration" :min="1" :max="12" />
                        <span style="margin-left:8px;" v-if="form.skuName == 'monthly'">月</span>
                        <a-input-number v-if="form.skuName == 'daily'" v-model:value="form.duration" :min="1" :max="100" />
                        <span style="margin-left:8px;" v-if="form.skuName == 'daily'">日</span>
                        <a-input-number v-if="form.skuName == 'weekly'" v-model:value="form.duration" :min="1" :max="100" />
                        <span style="margin-left:8px;" v-if="form.skuName == 'weekly'">周</span>
                    </a-form-item>

                    <a-form-item label="自动续费"
                        v-if="['daily', 'weekly', 'monthly'].includes(form.skuName) && fromTitle == '确认开机'">
                        <a-switch class="ml-8" v-model:checked="form.autoRenew"
                            :disabled="(accountInfo.balance < totalPrice * 2)"></a-switch>
                    </a-form-item>

                    <a-form-item label="GPU" class="mb-8">
                        {{ instance?.Instance?.gpuName }}
                    </a-form-item>

                    <template v-if="form.skuName != 'free'">
                        <a-form-item label="实例单价" class="mb-8">
                            ￥{{ instance_price || 0 }}/ {{ formatUnit }}
                        </a-form-item>

                        <a-form-item label="开机后实例存储费用为" class="mb-8">
                            ￥{{ formatInstanceOpenFee }}/{{ formatUnit }}
                        </a-form-item>

                        <a-form-item label="费用金额" class="mb-8">
                            ￥ {{ totalPrice }}
                        </a-form-item>

                        <a-form-item label="账户可用余额" v-if="fromTitle == '确认开机'" class="mb-8">
                            ￥ {{ accountInfo.balance }}
                        </a-form-item>
                    </template>

                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { defineProps, defineEmits, computed, ref } from 'vue';
import { handleInstance } from 'api/modules/api.instance'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import userInfoStore from '@/stores/userInfo.js'
const useUserInfoStore = userInfoStore()
const { accountInfo } = storeToRefs(useUserInfoStore);

const router = useRouter()

const props = defineProps({
    modelValue: {
        type: Boolean,
    },
    instance: {
        type: Object,
        default: {}
    },
    fromTitle: {
        type: String,
        default: ''
    },
    setting: {
        type: Array,
        default: []
    }
});

const emit = defineEmits(['update:modelValue', 'handelOpt', 'handelNoBalance']);
const modalVisible = computed({
    get: () => props.modelValue,
    set: v => emit('update:modelValue', v),
});


// GPU卡数下拉  升配是机器剩余可用最大卡数，没有可用卡得时候只能降配
const useGpuNum = props.instance?.MachineResource?.gpuNum - props.instance?.MachineResource?.gpuNumUsed
let selectGpuNum
if(props?.fromTitle == '确认开机') {
    selectGpuNum = useGpuNum
}else {
    selectGpuNum = (parseFloat(props.instance?.Instance?.gpuNum) + useGpuNum)
}


const gpuNumOptions = Array.from(Array(selectGpuNum), function (value, index) {
    return {
        lable: index + 1,
        value: index + 1
    }
})

// skuName 
const form = ref({
    duration: 1
})

if (['payg', 'daily', 'weekly', 'monthly', 'free'].includes(props.instance?.Instance?.skuName)) {
    form.value.skuName = props.instance?.Instance?.skuName
} else {
    form.value.skuName = 'payg'
}

// 确定按钮的回调
const formRef = ref()
const gpuNum = ref(1)
const confirmLoading = ref(false)
const handleOk = () => {
    formRef.value.validateFields().then(() => {
        const params = {
            instanceId: props.instance?.Instance?.instanceId,
            method: props.fromTitle == '确认开机' ? 'start' : 'update',
            gpuNum: gpuNum.value,
            ...form.value,
            autoRenew: form.value.autoRenew ? 1 : 0
        }
        confirmLoading.value = true
        handleInstance(params).then(res => {
            confirmLoading.value = false
            if (res.code == 0) {
                emit('update:modelValue', false)
                emit('handelOpt', props.instance?.Instance?.instanceId)
            }
        }).catch(err => {
            confirmLoading.value = false
            if (err.code == 10111) {
                emit('update:modelValue', false)
                emit('handelNoBalance',  totalPriceFee.value)
            }
        })
    })

};

// 获取价格 开机保存价格open_instance_storage_price
const open_instance_storage_price = ref('')
const getPrice = () => {
    props.setting.forEach(item => {
        if (item.key == 'open_instance_storage_price') {
            open_instance_storage_price.value = item.value
        }
    })
}

getPrice()

// 获取实例单价
const instance_price = ref('')
const getInstancePrice = () => {
    const filterItem = props.instance?.MachineSku.find(item => {
        return item.skuName == form.value.skuName
    })
    instance_price.value = filterItem.price
}

getInstancePrice()

const selectSkuName = () => {
    if (!form.value.skuName) {
        return
    }

    const filterItem = props.instance?.MachineSku.find(item => {
        return item.skuName == form.value.skuName
    })

    instance_price.value = filterItem.price
}

// 费用金额 = 实例价格 + 存储价格
// 实例价格 = 机器sku价格 * 显卡数量 * 租用周期 * 用户实例折扣
const instanceFee = () => {
    let price = ''
    const filterItem = props.instance?.MachineSku.find(item => {
        return item.skuName == form.value.skuName
    })

    price = filterItem.price
    const duration = props.instance?.Order?.duration || 0
    const discount = accountInfo?.value?.userDiscount?.instanceDiscount || 1
    const countFee = price * (gpuNum.value || 1) * duration * discount
    return countFee.toFixed(2) || 0
}

// 存储价格
const formatStorageTotalFee = ref(0)
const formatInstanceOpenFee = computed(() => {
    const price = open_instance_storage_price.value || 0
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const storageNum = printGBSize(props.instance?.InstancePhysicalState?.systemDiskSize + props.instance?.InstancePhysicalState?.dataDiskSize)
    let duration = 0

    if (form.value.skuName == 'daily') {
        duration = 1 * 24 * form.value.duration
    } else if (form.value.skuName == 'weekly') {
        duration = 1 * 24 * 7 * form.value.duration
    } else if (form.value.skuName == 'monthly') {
        duration = 1 * 24 * 30 * form.value.duration
    } else {
        duration = 1
    }

    const countFee = price * storageNum * duration * discount
    formatStorageTotalFee.value = countFee.toFixed(2) || 0
    return countFee.toFixed(2) || 0
})

// 计算费用  实例价格 * 用户折扣 + 存储费用 - 代金券金额
const totalPriceFee = ref(0)
const totalPrice = computed(() => {
    let price = ''
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const voucherFee = props.instance?.Instance?.payByVoucher == 1 ? accountInfo?.value?.userTicket?.amount : 0

    const filterItem = props.instance?.MachineSku.find(item => {
        return item.skuName == form.value.skuName
    })

    price = (Number(formatStorageTotalFee.value) + parseFloat((filterItem?.price * form.value.duration * gpuNum.value * discount).toFixed(2)) - parseFloat(voucherFee)) < 0 ? 0 : Number(formatStorageTotalFee.value) + parseFloat((filterItem?.price * form.value.duration * gpuNum.value * discount).toFixed(2)) - parseFloat(voucherFee)

    totalPriceFee.value = price.toFixed(2) || 0
    return price.toFixed(2) || 0
})

//  GB内存计算
const printGBSize = val => {
    const GB = 1024 * 1024 * 1024
    if (!val) {
        return 0
    }

    return `${(val / GB).toFixed(2)}`
}

// 转换单位
const formatUnit = computed(() => {
    let str = ''
    if (form.value.skuName == 'daily') {
        str = '天 *' + form.value.duration
    } else if (form.value.skuName == 'weekly') {
        str = '周 *' + form.value.duration
    } else if (form.value.skuName == 'monthly') {
        str = '月 *' + form.value.duration
    } else {
        str = '小时'
    }

    return str
})


</script>

